<!--
 * @description 惠福商城-福利包
 * @author dumeng
 * @date 2021/7/28
 -->
<template>
  <div class="hfflb-page">
    <el-form ref="hfflbForm" :model="form" :rules="rules" label-width="190px">
      <el-form-item label="出金账户" prop="accountId">
        <el-select
          v-model="form.accountId"
          :disabled="!!id"
          placeholder="请选择"
          style="width: 100%"
          @change="handleAccChange"
        >
          <el-option
            v-for="(item, index) in accList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="isShowAcc" label="充值记录" prop="rechargeId">
        <el-select
          v-model="form.rechargeId"
          :disabled="!!id"
          placeholder="请选择"
          style="width: 100%"
        >
          <el-option
            v-for="(item, index) in rechList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="职工福利子账户类型" prop="classifType2">
        <div class="zgfl">
          <el-select
            v-model="form.classifType2"
            :disabled="!!id"
            placeholder="请选择"
            style="width: 100%"
            @change="handleAccountChange"
          >
            <el-option
              v-for="(item, index) in accounts"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <i class="el-icon-refresh refresh-i" @click="refresh" />
          <div
            v-if="!id"
            style=" font-size: 14px;
            color: #606266;"
          >如果没有职工福利子账户可选择，点击这里&nbsp;<el-tag style="cursor:pointer;" type="danger" @click="zgflzzhVisible=true, zgflzzhTime=new Date().getTime()">去创建</el-tag>&nbsp;福利子账户</div>
        </div>
        <br>
      </el-form-item>
      <el-form-item label="是否支持自有零钱支付" prop="isWelfarePay">
        <el-radio-group v-model="form.isWelfarePay">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否可同时使用其它子账户" prop="other">
        <el-radio-group v-model="form.other">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
        <el-form-item v-if="form.other===1" prop="otherSubAccountTypes">
          <qtzzh v-model="form.otherSubAccountTypes" :other-sub-account-type-map="form.otherSubAccountTypeMap" :classif-type2="form.classifType2" />
        </el-form-item>
      </el-form-item>
      <el-form-item label="定向发放金额(每人)上限" prop="userUpperLimit">
        <el-input
          v-model="form.userUpperLimit"
          oninput="value=value.replace(/^\.+|[^\d.]/g,'')"
          placeholder="请输入定向发放金额(每人)上限"
          @blur="myBlur"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <!--      <el-form-item label="惠福专区活动" prop="dataId">-->
      <!--        <el-select v-model="form.dataId" :disabled="!!id" placeholder="请选择" style="width: 100%" @change="handleJdChange">-->
      <!--          <el-option v-for="(item, index) in jdList" :key="index" :label="item.label" :value="item.value" />-->
      <!--        </el-select>-->
      <!--        <br>-->
      <!--        <div-->
      <!--          v-if="!id"-->
      <!--          style=" font-size: 14px;-->
      <!--          color: #606266;"-->
      <!--        >如果没有登记京东商城的对接信息，点击这里 &nbsp;<el-tag style="cursor:pointer;" type="danger" @click="jdhdVisible=true, jdhdTime=new Date().getTime()">去创建</el-tag>&nbsp;京东商城对接信息。</div>-->
      <!--      </el-form-item>-->
      <el-form-item label="专区活动" prop="dataId">
        <el-button v-if="form.dataId===''" type="primary" size="mini" @click="getArea">选择专区</el-button>

        <el-tag
          v-else
          :closable="!id"
          @close="resetDataId"
        >
          {{ form.areaName || '' }}
        </el-tag>
      </el-form-item>
      <el-form-item label="福利领取起止时间" prop="receiveTime">
        <el-date-picker
          v-model="form.receiveTime"
          style="width:70%"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="福利使用起止时间" prop="useTime">
        <el-date-picker
          v-model="form.useTime"
          style="width:70%"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        />
        &nbsp;&nbsp;<el-checkbox v-model="fit" @change="setEqualTime">与福利领取时间一致</el-checkbox>
      </el-form-item>
      <el-form-item label="使用说明" prop="explain">
        <el-input
          v-model="form.explain"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 6 }"
          placeholder="请输入使用说明"
        />
      </el-form-item>
    </el-form>
    <zgflzzh :key="zgflzzhTime" :visible.sync="zgflzzhVisible" @select="selectZgflzzh" />
    <jdhd :key="jdhdTime" :visible.sync="jdhdVisible" @select="selectJdhd" />
    <!--      选择专区-->
    <el-dialog
      v-el-drag-dialog
      v-loading="listLoading"
      custom-class="area"
      title="选择专区"
      :visible.sync="dialogVisible"
      width="70%"
    >
      <el-table :data="areaList">
        <el-table-column label width="35">
          <template slot-scope="scope">
            <el-radio v-model="radioObj" :label="scope.row">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column property="name" label="专区名称" width="150" />
        <el-table-column label="图片" width="200">
          <template slot-scope="scope">
            <el-image
              style="width: 150px; height: 150px"
              :src="scope.row.img"
              :preview-src-list="[scope.row.img]"
            />
          </template>
        </el-table-column>
        <el-table-column property="childAccount" label="子账户类型" width="150" />
        <el-table-column property="describe" label="说明" />
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.pageSize"
        @pagination="getArea"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setDataId">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import { getAcc, getRech, getJdRech, queryAccount, queryJd, getRechOne, getIsAcc, queryPageByArea } from '../api/index'
import zgflzzh from './zgflzzh'
import qtzzh from './/qtzzh'
import jdhd from './/jdhd'
import CryptoJS from '@/utils/aesJiaJM'
import Pagination from '@/components/Pagination'
import elDragDialog from '@/directive/el-drag-dialog'
export default {
  name: 'Hfflb',
  components: { zgflzzh, qtzzh, jdhd, Pagination },
  directives: { elDragDialog },
  props: {
    data: {
      type: Object,
      default: () => {}
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      zgflzzhVisible: false,
      zgflzzhTime: new Date().getTime() + 1,
      jdhdTime: new Date().getTime() + 2,
      jdhdVisible: false,
      isHaveAcc: '', // （系统配置）本企业出金账户是否需要选择充值记录：0  不需要充值记录    1 需要
      isShowAcc: false, // 是否展示充值记录选择框
      accList: [], // 出金账户
      rechList: [], // 充值记录
      accounts: [], // 职工福利子账户类型
      jdList: [], // 惠福专区活动
      fit: true,
      form: {
        accountId: '',
        rechargeId: '',
        classifType2: '',
        dataId: '',
        areaName: '',
        isWelfarePay: 2,
        other: 1,
        areaImg: '', // 特殊字段，对应专区的url
        otherSubAccountTypes: '',
        otherSubAccountTypeMap: {},
        userUpperLimit: '',
        receiveTime: '',
        useTime: '',
        explain: '',
        areasubAcntTps: ''
      },
      rules: {
        accountId: [{
          required: true,
          message: '请选择出金账户',
          trigger: 'change'
        }],
        rechargeId: [{
          required: true,
          message: '请选择充值记录',
          trigger: 'change'
        }],
        dataId: [{
          required: true,
          message: '请选择惠福专区活动',
          trigger: 'change'
        }],
        classifType2: [{
          required: true,
          message: '请选择职工福利子账户类型',
          trigger: 'change'
        }],
        isWelfarePay: [{
          required: true,
          message: '请选择是否支持自有零钱支付',
          trigger: 'change'
        }],
        other: [{
          required: true,
          message: '请选择是否可同时使用其它子账户',
          trigger: 'change'
        }],
        userUpperLimit: [
          { required: true, message: '请输入定向发放金额(每人)上限', trigger: 'blur' }
        ],
        otherSubAccountTypes: [{
          required: true,
          message: '请添加可同时使用子账户',
          trigger: 'blur'
        }],
        receiveTime: [{
          required: true,
          message: '请选择福利领取起止时间',
          trigger: 'change'
        }],
        useTime: [{
          required: true,
          message: '请选择福利使用起止时间',
          trigger: 'change'
        }],
        explain: [{
          required: true,
          message: '请填写使用说明',
          trigger: 'blur'
        }]
      },
      listLoading: false,
      areaList: [],
      dialogVisible: false,
      total: 0,
      radioObj: {},
      listQuery: {
        page: 1,
        pageSize: 10
      }
    }
  },
  watch: {
    'form.receiveTime'(val) {
      const startTime = val ? val[0] : ''
      const endTime = val ? val[1] : ''
      if (this.fit) {
        this.$set(this.form, 'useTime', val)
      }
      if (val && this.form.useTime && startTime === this.form.useTime[0] && endTime === this.form.useTime[1]) {
        this.fit = true
      }
    },
    'form.useTime'(val) {
      const startTime = val ? val[0] : ''
      const endTime = val ? val[1] : ''
      if (val && this.form.receiveTime && startTime === this.form.receiveTime[0] && endTime === this.form.receiveTime[1]) {
        this.fit = true
      }
    }
  },
  async created() {
    this.$bus.$on('refresh', this.refresh)
    this.isHaveAcc = await this.getIsAccFun()
    this.accList = await this.getAccFun()
    this.accounts = await this.getAccounts()
    this.jdList = await this.queryJdFun()
    if (this.data && this.data.rechargeId && this.data.rechargeId !== '-1') {
      this.rechList = await this.getRechOneFun(this.data.rechargeId)
      this.isShowAcc = !!this.data.rechargeId
    }
    if (this.data && this.data.classifType2) {
      for (const i in this.form) {
        if (i === 'otherSubAccountTypeMap') {
          this.$set(this.form, i, this.data[i] || {})
        } else {
          this.$set(this.form, i, this.data[i] || '')
        }
      }
      this.form.receiveTime = [this.data.receiveStarttime, this.data.receiveEndtime]
      this.form.useTime = [this.data.expirationStartdate, this.data.expirationDate]
      delete this.form.receiveStarttime
      delete this.form.receiveEndtime
      delete this.form.expirationStartdate
      delete this.form.expirationDate
      this.form.other = this.data.otherSubAccountTypes ? 1 : 2
    }
  },
  beforeDestroy() {
    this.$bus.$off('refresh', this.refresh)
  },
  methods: {
    getArea() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryPageByArea(this.listQuery).then((res) => {
          this.areaList = res.data.data.rows
          this.total = res.data.data.total
          this.listLoading = false
          this.dialogVisible = true
          loading.close()
        }).catch(error => {
          reject(error)
          loading.close()
        })
      })
    },
    resetDataId() {
      this.form.dataId = ''
      this.form.areaName = ''
      this.form.areasubAcntTps = ''
      this.radioObj = ''
    },
    setDataId() {
      if (!this.radioObj) {
        this.$message.error('请选择专区')
        return
      }
      console.log(this.radioObj)
      this.form.dataId = this.radioObj.id
      this.form.areaName = this.radioObj.name
      this.form.areasubAcntTps = this.radioObj.childAccount
      this.form.areaImg = this.radioObj.prefectureUrl
      this.dialogVisible = false
    },
    // 选择惠福专区活动的回调
    async selectJdhd(val) {
      this.jdList = await this.queryJdFun()
      this.form.dataId = val
    },
    queryJdFun() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        queryJd({ }).then(res => {
          loading.close()
          const arr = res.data.data || []
          const arr2 = arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.activityName}-${a.activityCode}[${a.status == ' ZT02' ? '禁用' : '启用'}]${a.startDate ? '[' + this.formatTime(a.startDate) + '至' : ''}${a.endDate ? this.formatTime(a.endDate) + ']' : ''}`
          }))
          resolve(arr2)
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handleJdChange(value) {
      const obj = this.jdList.find(a => a.id === value)
      // 使用状态为：${obj.statusValue}，
      this.$alert(`您选择的惠福专区活动是：${obj.activityName}，状态为：${obj.statusValue}，
			  ${obj.startDate ? '有效期是：' + this.formatTime(obj.startDate) + '至' : ''}
			  ${obj.endDate ? this.formatTime(obj.endDate) + ']' : ''}`, '提示', {
        confirmButtonText: '确定',
        callback: action => {
          this.form.expirationStartdate = obj.startDate
          this.form.receiveStarttime = obj.startDate
          this.form.expirationDate = obj.endDate
          this.form.receiveEndtime = obj.endDate
        }
      })
    },
    setEqualTime(val) {
      if (val && this.form.receiveTime) {
        this.$set(this.form, 'useTime', this.form.receiveTime)
      } else {
        this.$set(this.form, 'useTime', '')
      }
    },
    myBlur(e) {
      this.form.userUpperLimit = e.target.value
    },
    /**
     * 选择职工福利子账户
     * @param subAcntTp
     */
    async selectZgflzzh(subAcntTp) {
      await this.getAccounts().then(res => {
        this.accounts = res
        this.form.classifType2 = subAcntTp
        this.zgflzzhVisible = false
        this.zgflzzhTime = new Date().getTime()
      })
    },
    // 切换子账户
    handleAccountChange(value) {
      const obj = this.accounts.find(a => a.subAcntTp === value)
      this.$alert(`您选择的付款子帐户是：${obj.subAcntNm}，状态为：${obj.subAcntSt == 1 ? '禁用' : '启用'}，
        ${obj.subAcntStartTm ? '有效期是：' + this.formatTime(obj.subAcntStartTm) + '至' : ''}
        ${obj.subAcntEndTm ? this.formatTime(obj.subAcntEndTm) + ']' : ''}`, '提示', {
        confirmButtonText: '确定'
      }).then(() => {
        // 如果使用其他子账户中含有当前选择的账户，则删除其他子账户中的当前账户
        const otherSubAccountTypes = this.form.otherSubAccountTypes.split(',').filter(item => {
          return item !== value
        }).join(',')
        this.$set(this.form, 'otherSubAccountTypes', otherSubAccountTypes)
      })
    },
    // 切换出金账户
    async handleAccChange(val) {
      const isEnterprise = this.accList.find(item => { return item.id === val }).isEnterprise
      this.form.rechargeId = ''
      // 如果选择本企业账户需要充值记录且当前选择的出金账户为本企业
      if (this.isHaveAcc === '0' && isEnterprise === 'SFQYZY_YES') {
        this.isShowAcc = false
      } else {
        this.rechList = await this.getRechList(val)
        this.isShowAcc = true
      }
    },
    // 获取职工福利子账户
    getAccounts() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        queryAccount({
          giveInfoId: this.id,
          isOpen: 1
        }).then(res => {
          loading.close()
          const arr = res.data.data || []
          const list = arr.map(a => ({
            ...a,
            value: a.subAcntTp,
            label: `${a.subAcntTp}-${a.subAcntNm}[${a.subAcntSt == 1 ? '禁用' : '启用'}]${a.subAcntStartTm ? '[' + this.formatTime(a.subAcntStartTm) + '至' : ''}${a.subAcntEndTm ? this.formatTime(a.subAcntEndTm) + ']' : ''}`
          }))
          resolve(list)
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    formatTime(str) {
      return str && str.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6')
    },
    // 获取是否需要出金账户
    getIsAccFun() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getIsAcc({ name: 'ACCOUNT_IS_ADD_RECHARGE' }).then(res => {
          loading.close()
          resolve(res.data.data.configValue)
        }).catch(() => {
          loading.close()
          resolve('0')
        })
      })
    },
    // 获取出金账户
    getAccFun() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        const query = this.id ? { status: 'ZHZT01' } : {}
        getAcc(query).then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.name}(${CryptoJS.$aesJieM(a.accountNumber)})`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    async getRechListFun(id) {
      this.rechList = await this.getRechOneFun(id)
    },
    getRechOneFun(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getRechOne({ rechargeId: id }).then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.applyName}(${a.rechargeAmount}元)`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    // 获取充值记录
    getRechList(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getJdRech({
          accountId: id
        }).then(res => {
          loading.close()
          const arr = res.data.data || []
          resolve(arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.applyName}(${a.rechargeAmount}元)`
          })))
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    validateForm() {
      return new Promise((resolve) => {
        this.$refs['hfflbForm'].validate((valid) => {
          if (valid) {
            const formData = Object.assign({}, this.form)
            formData.otherSubAccountTypes = formData.other === 0 ? '' : formData.otherSubAccountTypes
            formData.receiveStarttime = formData.receiveTime ? formData.receiveTime[0] : ''
            formData.receiveEndtime = formData.receiveTime ? formData.receiveTime[1] : ''
            formData.expirationStartdate = formData.useTime ? formData.useTime[0] : ''
            formData.expirationDate = formData.useTime ? formData.useTime[1] : ''
            delete formData.receiveTime
            delete formData.useTime
            delete formData.otherSubAccountTypeMap
            resolve(formData)
          } else {
            resolve('')
          }
        })
      })
    },
    async refresh() {
      this.accounts = await this.getAccounts()
    }
  }
}
</script>

<style scoped lang="scss">
.zgfl{

  position: relative;
  .refresh-i{
    color:#ccc;
    padding-left:8px;
    cursor:pointer;
    position: absolute;
    right:-28px;
    top:5px;
    font-size: 26px;
  }
}

</style>
